package hesso.smartdraw.ch;

import hesso.smartdraw.ch.db.DBHelper;
import hesso.smartdraw.ch.guielements.Button;
import hesso.smartdraw.ch.guielements.ButtonSprite;
import hesso.smartdraw.ch.guielements.Grid;
import hesso.smartdraw.ch.guielements.LevelSwitcher;
import hesso.smartdraw.ch.guielements.RoomEditButton;
import hesso.smartdraw.ch.guielements.SnapDot;
import hesso.smartdraw.ch.guielements.WallLine;
import hesso.smartdraw.ch.guielements.WallMoveDot;
import hesso.smartdraw.ch.model.Building;
import hesso.smartdraw.ch.model.Color;
import hesso.smartdraw.ch.model.Level;
import hesso.smartdraw.ch.model.Room;
import hesso.smartdraw.ch.model.User;
import hesso.smartdraw.ch.model.Wall;
import hesso.smartdraw.ch.multitouch.MultiTouch;
import hesso.smartdraw.ch.multitouch.MultiTouchController;
import hesso.smartdraw.ch.multitouch.MultiTouchException;
import hesso.smartdraw.ch.multitouch.PinchZoomDetector;
import hesso.smartdraw.ch.multitouch.PinchZoomDetector.IPinchZoomDetectorListener;

import java.util.ArrayList;

import org.anddev.andengine.engine.Engine;
import org.anddev.andengine.engine.camera.ZoomCamera;
import org.anddev.andengine.engine.camera.hud.HUD;
import org.anddev.andengine.engine.options.EngineOptions;
import org.anddev.andengine.engine.options.EngineOptions.ScreenOrientation;
import org.anddev.andengine.engine.options.resolutionpolicy.RatioResolutionPolicy;
import org.anddev.andengine.entity.scene.Scene;
import org.anddev.andengine.entity.scene.Scene.IOnSceneTouchListener;
import org.anddev.andengine.entity.scene.background.ColorBackground;
import org.anddev.andengine.entity.sprite.Sprite;
import org.anddev.andengine.entity.util.FPSLogger;
import org.anddev.andengine.input.touch.TouchEvent;
import org.anddev.andengine.input.touch.detector.ScrollDetector;
import org.anddev.andengine.input.touch.detector.ScrollDetector.IScrollDetectorListener;
import org.anddev.andengine.input.touch.detector.SurfaceScrollDetector;
import org.anddev.andengine.opengl.texture.Texture;
import org.anddev.andengine.opengl.texture.TextureOptions;
import org.anddev.andengine.opengl.texture.region.TextureRegion;
import org.anddev.andengine.opengl.texture.region.TextureRegionFactory;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Display;
import android.widget.Toast;

/**
 * @author Nicolas Gramlich
 * @since 15:44:58 - 05.11.2010
 */
public class DrawWallScreen extends Base implements IOnSceneTouchListener, IScrollDetectorListener, IPinchZoomDetectorListener {
        // ===========================================================
        // Constants
        // ===========================================================

        // ===========================================================
        // Fields
        // ===========================================================

        private ZoomCamera mZoomCamera;
        
        private Texture mTexture;
        private TextureRegion mFaceTextureRegion;
        
        private Display display;
        
        private static final int VIEWBUTTONHEIGHT = 300;
        private static final int VIEWBUTTONWIDTH = 300;

        private SurfaceScrollDetector mScrollDetector;
        private PinchZoomDetector mPinchZoomDetector;
        private float mPinchZoomStartedCameraZoomFactor;
        final Scene scene = new Scene(1);
        
    	private WallLine tempWallLine;
    	private ArrayList<WallLine> walls = new ArrayList<WallLine>();
    	private ArrayList<WallLine> tempRoom = new ArrayList<WallLine>();
    	private Level theLevel;
    	private User theUser = new User(1, "trololo");
    	private Building building;
    	private boolean unfinishedRoom = false;
    	private DBHelper dbHelper;
        
        private boolean editMode = false;
        
        private boolean gridIsVisible = true;

        // ===========================================================
        // Constructors
        // ===========================================================

        // ===========================================================
        // Getter & Setter
        // ===========================================================

        // ===========================================================
        // Methods for/from SuperClass/Interfaces
        // ===========================================================

        @Override
        public Engine onLoadEngine() {
        	display = getWindowManager().getDefaultDisplay(); 
        	
            this.mZoomCamera = new ZoomCamera(0, 0, display.getWidth(), display.getHeight());
            final Engine engine = new Engine(new EngineOptions(true, ScreenOrientation.LANDSCAPE, new RatioResolutionPolicy(display.getWidth(), display.getHeight()), this.mZoomCamera));

            try {
                    if(MultiTouch.isSupported(this)) {
                            engine.setTouchController(new MultiTouchController());
                    } else {
                            //Toast.makeText(this, "Sorry your device does NOT support MultiTouch!\n\n(No PinchZoom is possible!)", Toast.LENGTH_LONG).show();
                    }
            } catch (final MultiTouchException e) {
                    //Toast.makeText(this, "Sorry your Android Version does NOT support MultiTouch!\n\n(No PinchZoom is possible!)", Toast.LENGTH_LONG).show();
            }
            return engine;
        }

        @Override
        public void onLoadResources() {
			dbHelper = DBHelper.getInstance(this);
        	dbHelper.initDBConn();
        	final Bundle extras = getIntent().getExtras();
        	int buildingId = extras.getInt("buildingId");
        	int level = extras.getInt("level");        	
        	
        	// Replace with DB 
        	
        	building = dbHelper.getBuildingByBuildingId(buildingId);      
        	selectLevel(level);
    		//createEditRoomButton(theLevel.getRoomArray().get(0));
        	if(theLevel.getRoomArray().size() != 0)
        		addRoomsToScreen(theLevel.getRoomArray());
        }
        
        private void selectLevel(int whished){  
        	for(int i = 0; i < building.getLevelArray().size(); i++){
        		if(building.getLevelArray().get(i).getLevel() == whished){
            		this.theLevel = building.getLevelArray().get(i);   
            		return;
        		}
        	}      	
        	this.theLevel = building.getLevelArray().get(0);     	  
        }
        
        private ArrayList<hesso.smartdraw.ch.guielements.Level> getLevels(boolean aboveZero, TextureRegion levelTextureRegion){
        	ArrayList<hesso.smartdraw.ch.guielements.Level> lvls = new ArrayList<hesso.smartdraw.ch.guielements.Level>();
        	for(int i = 0; i < building.getLevelArray().size(); i++){
        		if(aboveZero){
	        		if(building.getLevelArray().get(i).getLevel() >= 0){
	        			if(building.getLevelArray().get(i) == this.theLevel)
	        				lvls.add(new hesso.smartdraw.ch.guielements.Level(0.0f, 0.0f, levelTextureRegion, building.getLevelArray().get(i).getLevel(), this, true));
	        			else
	        				lvls.add(new hesso.smartdraw.ch.guielements.Level(0.0f, 0.0f, levelTextureRegion, building.getLevelArray().get(i).getLevel(), this, false));
	        		}
        		}else{
        			if(building.getLevelArray().get(i).getLevel() < 0){
	        			if(building.getLevelArray().get(i) == this.theLevel)
	        				lvls.add(new hesso.smartdraw.ch.guielements.Level(0.0f, 0.0f, levelTextureRegion, building.getLevelArray().get(i).getLevel(), this, true));
	        			else
	        				lvls.add(new hesso.smartdraw.ch.guielements.Level(0.0f, 0.0f, levelTextureRegion, building.getLevelArray().get(i).getLevel(), this, false));
        			}
        		}
        	}
        	return lvls;
        }

        @Override
        public Scene onLoadScene() {
                this.mEngine.registerUpdateHandler(new FPSLogger());

                scene.setOnAreaTouchTraversalFrontToBack();

                scene.setBackground(new ColorBackground(0.2980f, 0.5372f, 0.7294f));

                this.mScrollDetector = new SurfaceScrollDetector(this);
                if(MultiTouch.isSupportedByAndroidVersion()) {
                        try {
                                this.mPinchZoomDetector = new PinchZoomDetector(this);
                        } catch (final MultiTouchException e) {
                                this.mPinchZoomDetector = null;
                        }
                } else {
                        this.mPinchZoomDetector = null;
                }

                scene.setOnSceneTouchListener(this);
                scene.setTouchAreaBindingEnabled(true);
                
                
                final Grid grid = new Grid(scene, display.getWidth(), display.getHeight(), 20);
                grid.drawGrid();
                
                HUD hud = new HUD();
                
                Texture levelUpIconTexture = new Texture(32, 32, TextureOptions.BILINEAR_PREMULTIPLYALPHA);
                TextureRegion levelUpIconTextureRegion = TextureRegionFactory.createFromAsset(levelUpIconTexture, this, "icons/levelUpIcon.png", 0, 0);
                this.mEngine.getTextureManager().loadTexture(levelUpIconTexture);
                
                Texture levelUpMinIconTexture = new Texture(32, 32, TextureOptions.BILINEAR_PREMULTIPLYALPHA);
                TextureRegion levelUpMinIconTextureRegion = TextureRegionFactory.createFromAsset(levelUpMinIconTexture, this, "icons/levelUpMinIcon.png", 0, 0);
                this.mEngine.getTextureManager().loadTexture(levelUpMinIconTexture);
                
                Texture levelDownIconTexture = new Texture(32, 32, TextureOptions.BILINEAR_PREMULTIPLYALPHA);
                TextureRegion levelDownIconTextureRegion = TextureRegionFactory.createFromAsset(levelDownIconTexture, this, "icons/levelDownIcon.png", 0, 0);
                this.mEngine.getTextureManager().loadTexture(levelDownIconTexture);
                
                Texture levelDownMinIconTexture = new Texture(32, 32, TextureOptions.BILINEAR_PREMULTIPLYALPHA);
                TextureRegion levelDownMinIconTextureRegion = TextureRegionFactory.createFromAsset(levelDownMinIconTexture, this, "icons/levelDownMinIcon.png", 0, 0);
                this.mEngine.getTextureManager().loadTexture(levelDownMinIconTexture);
                
                Texture levelTexture = new Texture(32, 32, TextureOptions.BILINEAR_PREMULTIPLYALPHA);
                TextureRegion levelTextureRegion = TextureRegionFactory.createFromAsset(levelTexture, this, "icons/levelIcon.png", 0, 0);
                this.mEngine.getTextureManager().loadTexture(levelTexture);
               
                
                LevelSwitcher levelSwitcher = new LevelSwitcher(hud, display.getWidth(), display.getHeight(), 
                		this.getLevels(true, levelTextureRegion), this.getLevels(false, levelTextureRegion), //this.getLevels(false),
                		levelUpIconTextureRegion, levelUpMinIconTextureRegion,
                		levelDownIconTextureRegion, levelDownMinIconTextureRegion,
                		levelTextureRegion, this);
                mZoomCamera.setHUD(hud);
                
                this.mTexture = new Texture(1024, 1024, TextureOptions.BILINEAR_PREMULTIPLYALPHA);
                this.mFaceTextureRegion = TextureRegionFactory.createFromAsset(this.mTexture, this, "logo/fireflyBlackLogo.png", 0, 0);

                this.mEngine.getTextureManager().loadTexture(this.mTexture);
                
                final Sprite logo = new Sprite(-320, 340, this.mFaceTextureRegion);
                
                logo.setScale(0.3f);
                
                this.mTexture = new Texture(64, 64, TextureOptions.BILINEAR_PREMULTIPLYALPHA);
                this.mFaceTextureRegion = TextureRegionFactory.createFromAsset(this.mTexture, this, "icons/editIcon.png", 0, 0);
                this.mEngine.getTextureManager().loadTexture(this.mTexture);
                
                ButtonSprite changetoEditModeButton = new ButtonSprite(10,10,this.mFaceTextureRegion) {
					
					@Override
					public void actionUp() {
						if(editMode) {
                            
                            Toast.makeText(DrawWallScreen.this, "You are already in Edit Mode", Toast.LENGTH_SHORT).show();    
                            
                    } else {
                            
                            editMode = true;
                            Toast.makeText(DrawWallScreen.this, "Edit Mode", Toast.LENGTH_SHORT).show();
                            
                    };  
					}
					
					@Override
					public void actionMove() {
						// TODO Auto-generated method stub
						
					}
					
					@Override
					public void actionDown() {
						// TODO Auto-generated method stub
						
					}
				};
				
				this.mTexture = new Texture(64, 64, TextureOptions.BILINEAR_PREMULTIPLYALPHA);
                this.mFaceTextureRegion = TextureRegionFactory.createFromAsset(this.mTexture, this, "icons/viewIcon.png", 0, 0);
                this.mEngine.getTextureManager().loadTexture(this.mTexture);
                
                ButtonSprite changetoViewModeButton = new ButtonSprite(84,10,this.mFaceTextureRegion) {
					
					@Override
					public void actionUp() {
						if(editMode) {
                            editMode = false;
                            Toast.makeText(DrawWallScreen.this, "View Mode", Toast.LENGTH_SHORT).show();    
                            
                    } else {
                            
                            Toast.makeText(DrawWallScreen.this, "You are already in View Mode", Toast.LENGTH_SHORT).show();
                            
                    };  
					}
					
					@Override
					public void actionMove() {
						// TODO Auto-generated method stub
						
					}
					
					@Override
					public void actionDown() {
						// TODO Auto-generated method stub
						
					}
				};
				
				this.mTexture = new Texture(64, 64, TextureOptions.BILINEAR_PREMULTIPLYALPHA);
                this.mFaceTextureRegion = TextureRegionFactory.createFromAsset(this.mTexture, this, "icons/houseIcon.png", 0, 0);
                this.mEngine.getTextureManager().loadTexture(this.mTexture);
                ButtonSprite goBackButton = new ButtonSprite(display.getWidth() - 74,10,this.mFaceTextureRegion) {
					
					@Override
					public void actionUp() {
						Intent intent = new Intent(DrawWallScreen.this, LoginRegisterScreen.class);
                        startActivity(intent); 
					}
					
					@Override
					public void actionMove() {
						// TODO Auto-generated method stub
						
					}
					
					@Override
					public void actionDown() {
						// TODO Auto-generated method stub
						
					}
				};
				
				this.mTexture = new Texture(64, 64, TextureOptions.BILINEAR_PREMULTIPLYALPHA);
                this.mFaceTextureRegion = TextureRegionFactory.createFromAsset(this.mTexture, this, "icons/saveIcon.png", 0, 0);
                this.mEngine.getTextureManager().loadTexture(this.mTexture);
                
             
               
            
                
                hud.attachChild(changetoEditModeButton);
            	hud.registerTouchArea(changetoEditModeButton);
            	hud.attachChild(changetoViewModeButton);
            	hud.registerTouchArea(changetoViewModeButton);
            	hud.attachChild(goBackButton);
            	hud.registerTouchArea(goBackButton);

            	
            	hud.attachChild(logo);



                return scene;
                
        }

        @Override
        public void onLoadComplete() {

        }

        @Override
        public void onScroll(final ScrollDetector pScollDetector, final TouchEvent pTouchEvent, final float pDistanceX, final float pDistanceY) {
                final float zoomFactor = this.mZoomCamera.getZoomFactor();
                this.mZoomCamera.offsetCenter(-pDistanceX / zoomFactor, -pDistanceY / zoomFactor);
        }

        @Override
        public void onPinchZoomStarted(final PinchZoomDetector pPinchZoomDetector, final TouchEvent pTouchEvent) {
                this.mPinchZoomStartedCameraZoomFactor = this.mZoomCamera.getZoomFactor();
        }

        @Override
        public void onPinchZoom(final PinchZoomDetector pPinchZoomDetector, final TouchEvent pTouchEvent, final float pZoomFactor) {
                this.mZoomCamera.setZoomFactor(this.mPinchZoomStartedCameraZoomFactor * pZoomFactor);
        }

        @Override
        public void onPinchZoomFinished(final PinchZoomDetector pPinchZoomDetector, final TouchEvent pTouchEvent, final float pZoomFactor) {
                this.mZoomCamera.setZoomFactor(this.mPinchZoomStartedCameraZoomFactor * pZoomFactor);
        }


        @Override
        public boolean onSceneTouchEvent(final Scene pScene, final TouchEvent pSceneTouchEvent) {
        	Log.d("touch", "WholeScene");
        	if(editMode) {        		
        		switch(pSceneTouchEvent.getAction()) {        		
                case TouchEvent.ACTION_DOWN:

    				if(this.getTempWallRect() == null){
    					if(this.unfinishedRoom){
 
	    					this.setTempWallLine(new WallLine(
	    							this.tempRoom.get(this.tempRoom.size() - 1).getX2(),
	    							this.tempRoom.get(this.tempRoom.size() - 1).getY2(), 
									pSceneTouchEvent.getX(),
									pSceneTouchEvent.getY()));    	    						
    					}else{
	    					this.setTempWallLine(new WallLine(
	    							pSceneTouchEvent.getX(), 
									pSceneTouchEvent.getY(), 
									pSceneTouchEvent.getX() + 10,
									pSceneTouchEvent.getY() + 10));      	
    					}
    				}
                    break;

                case TouchEvent.ACTION_MOVE:
                	if(this.getTempWallRect() != null){

    					this.getTempWallRect().setPosition(
    							this.getTempWallRect().getX1(), 
    							this.getTempWallRect().getY1(), 
    							pSceneTouchEvent.getX(), 
    							pSceneTouchEvent.getY());
    				}
                    break;
                case TouchEvent.ACTION_UP:
                	this.saveTempWall();
                    break;
        		}
        		
        	} else {        		
        		if(this.mPinchZoomDetector != null) {
                    this.mPinchZoomDetector.onTouchEvent(pSceneTouchEvent);

                    if(this.mPinchZoomDetector.isZooming()) {
                            this.mScrollDetector.setEnabled(false);
                    } else {
                            if(pSceneTouchEvent.isActionDown()) {
                                    this.mScrollDetector.setEnabled(true);
                            }
                            this.mScrollDetector.onTouchEvent(pSceneTouchEvent);
                    }
        		} else {
                    this.mScrollDetector.onTouchEvent(pSceneTouchEvent);
        		}
        	}
        	
        	

                return true;
        }

        // ===========================================================
        // Methods
        // ===========================================================

        public Scene getScene() {
    		return scene;
    	}
        

    	public WallLine getTempWallRect(){
    		return this.tempWallLine;
    	}
    	

    	public void setTempWallLine(WallLine wLine){
    		if(wLine == null)
    			getScene().detachChild(this.tempWallLine );
    		else{
    			this.tempWallLine = wLine;
    			getScene().attachChild(wLine);
    		}
    	}
    	
    	private void addRoomsToScreen(ArrayList<Room> existingRooms){
    		ArrayList<WallLine> wlArr;
    		for(int i = 0; i < existingRooms.size(); i++){
    			wlArr = new ArrayList<WallLine>();
    			for(int j = 0; j < existingRooms.get(i).getWallArray().size(); j++){

    				wlArr.add(new WallLine(existingRooms.get(i).getWallArray().get(j)));
    				getScene().attachChild(wlArr.get(wlArr.size() -1));
    			}
    			createEditRoomButton(existingRooms.get(i));
    			createWallMoveDots(wlArr);
    		}
    	}
    	
    	public void createWallMoveDots(ArrayList<WallLine> walls){
    		//ArrayList<Wall> walls = room.getWallArray();
    		WallMoveDot dot;
    		for(int i = 0; i < walls.size(); i++){    			
    			if(i != walls.size() - 1){
    				dot = new WallMoveDot(walls.get(i), walls.get(i+1), this);
    				getScene().attachChild(dot);
    				getScene().registerTouchArea(dot);
    			}else{
    				dot = new WallMoveDot(walls.get(i), walls.get(0), this);
    				getScene().attachChild(dot);
    				getScene().registerTouchArea(dot);
    			}
    		}
  
    	}
    	
    	public void updateRoom(Wall w){
    		Room r = null;
    		for(int i = 0; i < this.theLevel.getRoomArray().size(); i++){
    			for(int j = 0; j < this.theLevel.getRoomArray().get(i).getWallArray().size(); j++){
    				if(this.theLevel.getRoomArray().get(i).getWallArray().get(j) == w){
    					r = this.theLevel.getRoomArray().get(i);
    				}
    			}
    		}
    		if(r != null){
    			this.dbHelper.saveRoom(r, this.theLevel.getId());
    			for(int i = this.scene.getChildCount() - 1; i >= 0; i--){
        			if(this.scene.getChild(i) instanceof RoomEditButton){
        				if(((RoomEditButton)this.scene.getChild(i)).getRoomId() == r.getId()){
        					this.scene.detachChild(this.scene.getChild(i));
        					break;
        				}    					    					
        			}
    			}    		
    			createEditRoomButton(r);
    		}
    	}
    	
    	private void removeTempFigures(){
    		for(int i = this.scene.getChildCount() - 1; i >= 0; i--){
    			if(this.scene.getChild(i) instanceof WallLine){
    				if(((WallLine)this.scene.getChild(i)).getModelWall() == null){
    					this.scene.detachChild(this.scene.getChild(i));
    				}    					    					
    			}
    			if(this.scene.getChild(i) instanceof SnapDot){
    				this.scene.detachChild(this.scene.getChild(i));
    			}
    		}
    	}
    	
    	public void saveTempWall(){
    		this.walls.add(this.tempWallLine);
    		this.tempRoom.add(this.tempWallLine);
    		
    		if(this.tempRoom.size() == 1){
        		getScene().attachChild(new SnapDot(tempWallLine.getX1(), tempWallLine.getY1(), 40, this));  			
    		}
    		
    		//getScene().attachChild(new SnapDot(tempWallLine.getX2(), tempWallLine.getY2(), 40, this));
    		
    		if(this.tempRoom.size() == 1){
    			unfinishedRoom = true;
    		}else{
        		if(tempRoom.get(0).getX1() == tempWallLine.getX2() && tempRoom.get(0).getY1() == tempWallLine.getY2()){
        			Room theNewRoom = createModelRoom(tempRoom);        			        		
        				// Save it to local DB
        			this.theLevel.addRoom(theNewRoom);   
        			//ArrayList<Room> existingRooms
        			ArrayList<Room> tmp = new ArrayList<Room>();
        			tmp.add(this.theLevel.getRoomArray().get(this.theLevel.getRoomArray().size() - 1));
        			addRoomsToScreen(tmp);
        			removeTempFigures();
        			this.tempRoom.clear();
        			
        			// TODO Remove old lines with all dependencies from screen
        			unfinishedRoom = false;
        		}    			
    		}
    		this.tempWallLine = null;
    	}
    	
    	public Room createModelRoom(ArrayList<WallLine> walls){
    		Room room = new Room();
    		for(int i = 0; i < walls.size(); i++){
    			room.addWall(new Wall(
    						(int)walls.get(i).getX1(), 
    						(int)walls.get(i).getY1(), 
    						(int)walls.get(i).getX2(), 
    						(int)walls.get(i).getY2(),
    						20, 20
    						)
    			);
    		}    		
    		return dbHelper.saveRoom(room, theLevel.getId());
    	}
    	
    	public void createEditRoomButton(Room room){
    		ArrayList<Wall> walls = room.getWallArray();
    		Button editBtn;
    		int buttonSize = 50;
    		int x = 0, y = 0;
    		
    		for(int i = 0; i < walls.size(); i++){
    			x += walls.get(i).getX1();
    			y += walls.get(i).getY1();
    		}
    		x = x / walls.size() - buttonSize / 2;
    		y = y / walls.size() - buttonSize / 2;
    		
    		editBtn = new RoomEditButton(x,y,buttonSize,buttonSize, Color.BLACK, room.getId(), DrawWallScreen.this, building.getId());
            
            getScene().attachChild(editBtn);
            getScene().registerTouchArea(editBtn);
    	}
    	
    	public void changeLevel(int level){	
    		Intent intent = new Intent(this, DrawWallScreen.class);
    		intent.putExtra("buildingId", this.building.getId());
        	intent.putExtra("level", level);        	
        	startActivity(intent);    		
    	}
    	
    	public int getNewLevel(boolean onTop){
    		int level = 0;
    		for(int i = 0; i < building.getLevelArray().size(); i++){
    			if(onTop){    				
    				if(building.getLevelArray().get(i).getLevel() >= level)
    					level = building.getLevelArray().get(i).getLevel() + 1;
    			}else{
    				if(building.getLevelArray().get(i).getLevel() <= level)
    					level = building.getLevelArray().get(i).getLevel() -1;    				
    			}
    		}
    		return level;
    	}
    	
    	public void addLevel(int lvl){
    		Level level = new Level("Unnamed level");
    		level.setLevel(lvl);
    		this.building.addLevel(level);
    		this.dbHelper.saveBuilding(this.building, theUser);
    	}
    	
    	public boolean deleteLevel(boolean top){
    		Level toDelete = this.building.getLevelArray().get(0);
    		for(int i = 0; i < this.building.getLevelArray().size(); i++){
    			if(top){
    				if(this.building.getLevelArray().get(i).getLevel() > toDelete.getLevel())
    					toDelete = this.building.getLevelArray().get(i);
    			}else{
    				if(this.building.getLevelArray().get(i).getLevel() < toDelete.getLevel())
    					toDelete = this.building.getLevelArray().get(i);
    			}
    		}
    		if(toDelete != this.theLevel && toDelete.getLevel() != 0){
    			// TODO: Replace with dbHelper delete Level function
    			this.building.getLevelArray().remove(toDelete);
    			//dbHelper.saveBuilding(this.building, theUser);
    			dbHelper.deleteLevelByLevelId(toDelete.getId());
    			return true;
    		}
    		return false;
    	}
    	
    	public int getActualLevelId(){
    		int level = this.theLevel.getLevel();
    		return level;
    	}

        // ===========================================================
        // Inner and Anonymous Classes
        // ===========================================================
}